package com.party.mobile.web.controller.crowdfund;

import com.google.common.collect.Maps;
import com.party.authorization.annotation.Authorization;
import com.party.common.constant.Constant;
import com.party.common.paging.Page;
import com.party.common.utils.PartyCode;
import com.party.common.utils.StringUtils;
import com.party.core.exception.BusinessException;
import com.party.core.model.counterfoil.Counterfoil;
import com.party.core.model.crowdfund.CrowdfundEvent;
import com.party.core.model.distributor.WithActivity;
import com.party.core.model.distributor.WithCount;
import com.party.core.model.member.Member;
import com.party.core.model.system.TargetType;
import com.party.core.service.counterfoil.ICounterfoilService;
import com.party.core.service.counterfoil.biz.CounterfoilBizService;
import com.party.core.service.crowdfund.ICrowdfundEventService;
import com.party.core.service.member.IMemberService;
import com.party.core.service.system.ISysConfigService;
import com.party.mobile.biz.crowdfund.RepresentBizService;
import com.party.mobile.biz.currentUser.CurrentUserBizService;
import com.party.mobile.biz.member.MemberBizService;
import com.party.mobile.web.annotation.SessionToken;
import com.party.mobile.web.annotation.VisitCollect;
import com.party.mobile.web.dto.AjaxResult;
import com.party.mobile.web.dto.crowdfund.output.GetRepresentOutput;
import com.party.mobile.web.dto.crowdfund.output.ListForTargetOutput;
import com.party.mobile.web.dto.crowdfund.output.RepresentForListOutput;
import com.party.mobile.web.dto.distributor.input.GetDistributorInput;
import com.party.mobile.web.dto.login.output.CurrentUser;
import com.party.mobile.web.dto.login.output.MemberOutput;
import com.party.mobile.web.interceptor.TokenInterceptor;
import com.vdurmont.emoji.EmojiParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 联合发起控制器
 * Created by wei.li
 *
 * @date 2017/3/2 0002
 * @time 14:02
 */

@Controller
@RequestMapping(value = "crowdfund/represent")
public class RepresentController {

    @Autowired
    private RepresentBizService representBizService;

    @Autowired
    private CurrentUserBizService currentUserBizService;

    @Autowired
    private MemberBizService memberBizService;

    @Autowired
    private IMemberService memberService;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private TokenInterceptor tokenInterceptor;

    @Autowired
    private ICounterfoilService counterfoilService;

    @Autowired
    private ICrowdfundEventService crowdfundEventService;

    Logger logger = LoggerFactory.getLogger(getClass());


    /**
     * 联合发起
     *
     * @param input   输入参数
     * @param result  验证参数
     * @param request 请求参数
     * @return 交互数据
     */
    @ResponseBody
    @Authorization
    @SessionToken(verify = true)
    @RequestMapping(value = "represent")
    public AjaxResult represent(@Validated GetDistributorInput input, BindingResult result, HttpServletRequest request) {
        AjaxResult ajaxResult = new AjaxResult();
        String currentId = null;
        try {
            if (result.hasErrors()) {
                List<ObjectError> allErrors = result.getAllErrors();
                String description = allErrors.get(0).getDefaultMessage();
                throw new BusinessException(PartyCode.PARAMETER_ILLEGAL, description);
            }
            if (StringUtils.isNotEmpty(input.getContent())) {
                if (sysConfigService.isConvertBase64()) {
                    input.setContent(StringUtils.encodeBase64(input.getContent()));
                } else {
                    input.setContent(EmojiParser.parseToAliases(input.getContent()));
                }
            }

            CurrentUser currentUser = memberBizService.bindPhoneBiz2(input.getMobile(), input.getVerifyCode(),
                    input.getCountryCode(), request);
            currentId = currentUser.getId();
            //如果字段为空 更新必要的用户信息
            Member curMember = memberBizService.updateImportantInfo(GetDistributorInput.transformMember(input), memberService.get(currentUser.getId()));
            MemberOutput memberOutput = memberBizService.getLoginMember(curMember);

            Map map = Maps.newHashMap();
            map.put("id", currentUser.getId());
            map.put("member", memberOutput);
            representBizService.represent(input, currentUser);
            return AjaxResult.success(map);
        } catch (BusinessException e) {
            Map map = Maps.newHashMap();
            map.put("id", currentId);
            tokenInterceptor.getToken(ajaxResult);
            ajaxResult.setErrorCode(e.getCode());
            ajaxResult.setDescription(e.getMessage());
            ajaxResult.setData(map);
            return ajaxResult;
        } catch (Exception e) {
            logger.error("代言异常", e);
            tokenInterceptor.getToken(ajaxResult);
            ajaxResult.setDescription("系统异常");
            return ajaxResult;
        }
    }

    /**
     * 获取联合发起信息
     *
     * @param input   输入参数
     * @param result  验证参数
     * @param request 请求参数
     * @return 交互数据
     */
    @ResponseBody
    @Authorization
    @RequestMapping(value = "getRepresent")
    @VisitCollect(module = TargetType.ZC_ACTIVITY)
    public AjaxResult getRepresent(@Validated GetDistributorInput input, BindingResult result, HttpServletRequest request) {
        AjaxResult ajaxResult = new AjaxResult();

        if (result.hasErrors()) {
            List<ObjectError> allErrors = result.getAllErrors();
            String description = allErrors.get(0).getDefaultMessage();
            ajaxResult.setErrorCode(PartyCode.PARAMETER_ILLEGAL);
            ajaxResult.setDescription(description);
            return ajaxResult;
        }

        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
        GetRepresentOutput getRepresentOutput;
        try {
            getRepresentOutput = representBizService.getRepresent(input, currentUser);
            CrowdfundEvent crowdfundEvent = crowdfundEventService.getCorwdfundByActivityId(getRepresentOutput.getId());
            List<Counterfoil> counterfoils = counterfoilService.findByBusinessId(crowdfundEvent.getId(), Constant.BUSINESS_TYPE_CROWDFUND);
            getRepresentOutput.setCounterfoils(counterfoils);
            if (StringUtils.isNotEmpty(getRepresentOutput.getDeclaration())) {
                if (sysConfigService.isConvertBase64()) {
                    getRepresentOutput.setDeclaration(StringUtils.decodeBase64New(getRepresentOutput.getDeclaration()));
                } else {
                    getRepresentOutput.setDeclaration(EmojiParser.parseToUnicode(getRepresentOutput.getDeclaration()));
                }
            }
        } catch (BusinessException be) {
            ajaxResult.setErrorCode(be.getCode());
            ajaxResult.setDescription(be.getMessage());
            return ajaxResult;
        } catch (Exception e) {
            e.printStackTrace();
            ajaxResult.setDescription("系统异常");
            return ajaxResult;
        }

        ajaxResult.setSuccess(true);
        ajaxResult.setData(getRepresentOutput);
        return ajaxResult;
    }

    /**
     * 联合发起列表
     *
     * @param page    分页参数
     * @param status  状态(0:进行中, 1:已经截止)
     * @param request 请求参数
     * @return 联合发起列表
     */
    @ResponseBody
    @Authorization
    @RequestMapping(value = "list")
    @VisitCollect(module = TargetType.ZC_ACTIVITY)
    public AjaxResult list(Page page, Integer status, HttpServletRequest request) {
        AjaxResult ajaxResult = new AjaxResult();
        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
        List<WithActivity> withActivityList;
        try {
            withActivityList = representBizService.list(page, status, currentUser);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxResult.setDescription("系统异常");
            return ajaxResult;
        }
        ajaxResult.setSuccess(true);
        ajaxResult.setData(withActivityList);
        ajaxResult.setPage(page);
        return ajaxResult;
    }


    /**
     * 项目下的联合发起
     *
     * @param id   项目编号
     * @param page 分页参数
     * @return 联合发起列表
     */
    @ResponseBody
    @RequestMapping(value = "listForTarget")
    public AjaxResult listForTarget(String id, Page page) {
        AjaxResult ajaxResult = new AjaxResult();

        List<ListForTargetOutput> listForTargetOutputList;
        try {
            listForTargetOutputList = representBizService.listForTarget(page, id);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxResult.setDescription("系统异常");
            return ajaxResult;
        }
        ajaxResult.setSuccess(true);
        ajaxResult.setData(listForTargetOutputList);
        ajaxResult.setPage(page);
        return ajaxResult;
    }


    /**
     * 编辑联合发起
     *
     * @param id          联合发起编号
     * @param declaration 联合发起宣言
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "edite")
    public AjaxResult edite(String id, String declaration, String style) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            if (StringUtils.isNotEmpty(declaration)) {
                if (sysConfigService.isConvertBase64()) {
                    declaration = StringUtils.encodeBase64(declaration);
                } else {
                    declaration = EmojiParser.parseToAliases(declaration);
                }
            }
            representBizService.edite(id, declaration, style);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxResult.setDescription("服务器异常");
            return ajaxResult;
        }
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }

    /**
     * 联合发起列表
     * @param withCount 查询参数
     * @param page 分页参数
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "listForActivity")
    public AjaxResult listForActivity(WithCount withCount, Page page){
        AjaxResult ajaxResult = new AjaxResult(true);

        List<RepresentForListOutput> representListForActivityOutputList;
        try {
            representListForActivityOutputList
                    = representBizService.listForActivity(withCount, page);
        } catch (Exception e) {
            ajaxResult.setSuccess(false);
            ajaxResult.setDescription("联合发起列表查询异常");
            return ajaxResult;
        }
        ajaxResult.setPage(page);
        ajaxResult.setData(representListForActivityOutputList);
        return ajaxResult;
    }

    /**
     * 联合发起列表
     *
     * @param page    分页参数
     * @param request 请求
     * @return
     */
    @ResponseBody
    @RequestMapping("myListForActivity")
    public AjaxResult myListForActivity(Page page, HttpServletRequest request) {
        AjaxResult ajaxResult = new AjaxResult(true);
        try {
            String currentId = currentUserBizService.getCurrentUser(request).getId();
            List<Map<String, Object>> representList = representBizService.myListForActivity(currentId, page);
            for (Map<String, Object> result : representList) {
                Integer inProgress = 0; // 是否进行中 1：进行中 0：已结束
                Date endTime = (Date) result.get("endTime");
                if (endTime.getTime() > System.currentTimeMillis()) {
                    inProgress = 1;
                }
                result.put("inProgress", inProgress);

                Object isMultiple = result.get("isMultiple");
                if (null != isMultiple) {
                    result.put("isMultiple", isMultiple.toString());
                }
            }
            ajaxResult.setData(representList);
        } catch (Exception e) {
            logger.error("联合发起列表查询异常", e);
            ajaxResult.setSuccess(false);
            ajaxResult.setDescription("联合发起列表查询异常");
            return ajaxResult;
        }
        ajaxResult.setPage(page);
        return ajaxResult;
    }
    /**
     * 项目下的联合发起___多场
     *
     * @param id   项目编号
     * @param page 分页参数
     * @return 联合发起列表
     */
    @ResponseBody
    @RequestMapping(value = "gradation/listForTarget")
    public AjaxResult gradationListForTarget(String id, Page page) {
        AjaxResult ajaxResult = new AjaxResult();

        List<ListForTargetOutput> listForTargetOutputList;
        try {
            listForTargetOutputList = representBizService.listForTarget(page, id);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxResult.setDescription("系统异常");
            return ajaxResult;
        }
        ajaxResult.setSuccess(true);
        ajaxResult.setData(listForTargetOutputList);
        ajaxResult.setPage(page);
        return ajaxResult;
    }

    /**
     * 获取联合发起信息
     *
     * @param input   输入参数
     * @param result  验证参数
     * @param request 请求参数
     * @return 交互数据
     */
    @ResponseBody
    @Authorization
    @RequestMapping(value = "gradation/getRepresent")
    @VisitCollect(module = TargetType.ZC_ACTIVITY)
    public AjaxResult gradationGetRepresent(@Validated GetDistributorInput input, BindingResult result, HttpServletRequest request) {
        AjaxResult ajaxResult = new AjaxResult();

        if (result.hasErrors()) {
            List<ObjectError> allErrors = result.getAllErrors();
            String description = allErrors.get(0).getDefaultMessage();
            ajaxResult.setErrorCode(PartyCode.PARAMETER_ILLEGAL);
            ajaxResult.setDescription(description);
            return ajaxResult;
        }

        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
        GetRepresentOutput getRepresentOutput;
        try {
            getRepresentOutput = representBizService.gradationGetRepresent(input, currentUser);

            if (StringUtils.isNotEmpty(getRepresentOutput.getDeclaration())) {
                if (sysConfigService.isConvertBase64()) {
                    getRepresentOutput.setDeclaration(StringUtils.decodeBase64New(getRepresentOutput.getDeclaration()));
                } else {
                    getRepresentOutput.setDeclaration(EmojiParser.parseToUnicode(getRepresentOutput.getDeclaration()));
                }
            }
        } catch (BusinessException be) {
            ajaxResult.setErrorCode(be.getCode());
            ajaxResult.setDescription(be.getMessage());
            return ajaxResult;
        } catch (Exception e) {
            e.printStackTrace();
            ajaxResult.setDescription("系统异常");
            return ajaxResult;
        }

        ajaxResult.setSuccess(true);
        ajaxResult.setData(getRepresentOutput);
        return ajaxResult;
    }
}
